package com.oceansoft.mobile.econsole.modules.movecar.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Strings;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.MD5Util;
import com.oceansoft.mobile.econsole.common.util.StringUtils;
import com.oceansoft.mobile.econsole.common.util.web.PageUtil;
import com.oceansoft.mobile.econsole.modules.api.service.IQueryService;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.ApiMessage;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.DriverLicenseSearchCondition;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.InQueryServiceInfo;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.VehicleSearchCondition;
import com.oceansoft.mobile.econsole.modules.jlapi.service.IJlApiService;
import com.oceansoft.mobile.econsole.modules.movecar.entity.Mes;
import com.oceansoft.mobile.econsole.modules.movecar.entity.MoveCar;
import com.oceansoft.mobile.econsole.modules.movecar.entity.MoveCarEntity;
import com.oceansoft.mobile.econsole.modules.movecar.entity.RoadBlock;
import com.oceansoft.mobile.econsole.modules.movecar.persistence.IMoveCarMapper;
import com.oceansoft.mobile.econsole.modules.movecar.service.IMoveCarService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/2/4.
 */
@Service
public class MoveCarServiceImpl extends CacheBaseService implements IMoveCarService {

    @Resource
    private IMoveCarMapper moveCarMapper;

    @Resource
    private IJlApiService jlApiService;

    @Resource
    private IQueryService queryService;

    @Override
    @Transactional
    public Result reportMoveCar(MultipartHttpServletRequest request) throws IOException {

        MoveCar moveCar = new MoveCar();
        moveCar.setAddress(request.getParameter("address"));
        moveCar.setCarNo(request.getParameter("carNo"));
        moveCar.setCarTypeId(request.getParameter("carTypeId"));


        moveCar.setReportMobile(request.getParameter("reportMobile"));
        moveCar.setReportAddress(request.getParameter("reportAddress"));
        moveCar.setReportIdCard(request.getParameter("reportIdCard"));
        moveCar.setReportName(request.getParameter("reportName"));
        moveCar.setReportTime(new Date());

        MultipartFile image = request.getFile("image");
        if(image.getSize() == 0){
            return new Result(Result.FAILURE,"请上传车辆图片");
        }else{
            String newFileName = String.format("%s%s", UUID.randomUUID().toString(), FileUtils.getExtName(image.getOriginalFilename()));
            String bizParentDir = configInfo.getBizDayDirRelPath(moveCar.getReportIdCard(), configInfo.getMoveCarDir());
            moveCar.setImageUrl(configInfo.getFileDownloadUrl(bizParentDir+"/"+newFileName));
            moveCar.setImageData(image.getBytes());
            //存储文件至文件系统
            image.transferTo(FileUtils.createFile(new File(String.format("%s/%s", configInfo.getFileUploadRootPath(), bizParentDir)), newFileName));
        }

        moveCar.setId(UUID.randomUUID().toString());
        int rt = moveCarMapper.saveMoveCar(moveCar);

        // TODO 调用118114接口
/*        // 查询车主信息，通知堵路车主
        String pushType = request.getParameter("pushType");
        String pushId = request.getParameter("pushId");
        if(StringUtils.isBlank(pushType)){
            return new Result(Result.FAILURE,"请输入推送渠道!");
        }
        if(StringUtils.isBlank(pushId)){
            return new Result(Result.FAILURE,"请输入推送对象!");
        }

        // 生成消息推送类（微信模板，极光，短信）
        ApiMessage message = queryService.getApiMessage(pushType,pushId);

        VehicleSearchCondition vehicleSearchCondition = new VehicleSearchCondition();
        vehicleSearchCondition.setJdchphm(moveCar.getCarNo());

        String command = JSON.toJSONString(vehicleSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_003, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        jlApiService.doMoveCarExecute(inQueryServiceInfo,message,moveCar);*/

        if(rt > 0){
            return new Result(Result.SUCC,"堵路移车上传成功");
        }

        return new Result(Result.FAILURE,"堵路移车上报失败");
    }

    public Pager<MoveCar> loadAllMoveCarsByPage(Query query){
        PageHelper.startPage(query.getPageNum(), query.getNumPerPage(), true);
        Page<MoveCar> page = (Page<MoveCar>) moveCarMapper.loadMoveCarsByCondition(query);
        return PageUtil.page2pager(page, query);
    }

    public Result loadMoveCarById(String id){
        MoveCar moveCar = moveCarMapper.findById(id);
        if(moveCar!=null){
            return new Result(moveCar);
        }else {
            return new Result(Result.FAILURE, "堵路移车数据不存在");
        }
    }

    public Result editMoveCar(MoveCar moveCar){
        int id = moveCarMapper.updateMoveCar(moveCar);
        if(id==1){
            return new Result(Result.SUCC,"更新成功");
        }
        return new Result(Result.FAILURE,"更新失败");
    }



    @Override
    public Result reportWxMoveCar(MoveCar moveCar) {
        int rt = 0;
        try {
            rt = moveCarMapper.saveMoveCar(moveCar);
        }catch(Exception e){
            e.printStackTrace();
        }

        // 查询车主信息，通知堵路车主
        if(StringUtils.isBlank(moveCar.getPushType())){
            return new Result(Result.FAILURE,"请输入推送渠道!");
        }
        if(StringUtils.isBlank(moveCar.getPushId())){
            return new Result(Result.FAILURE,"请输入推送对象!");
        }

        // 生成消息推送类（微信模板，极光，短信）
        ApiMessage message = queryService.getApiMessage(moveCar.getPushType(),moveCar.getPushId());

        VehicleSearchCondition vehicleSearchCondition = new VehicleSearchCondition();
        vehicleSearchCondition.setJdchphm(moveCar.getCarNo());

        String command = JSON.toJSONString(vehicleSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_003, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), "0:0:0:0:0:0:0:1", 0);

        jlApiService.doMoveCarExecute(inQueryServiceInfo,message,moveCar);

        if(rt > 0){
            return new Result(Result.SUCC,"堵路移车上传成功");
        }

        return new Result(Result.FAILURE,"堵路移车上报失败");
    }


    @Override
    public String  sendMsg(Mes message) throws IOException{
        String url = configInfo.getServiceInterfaceAddress() +"/message/sms/send";
        JSONObject object = JSON.parseObject(HttpClientUtil.doPostString(url,message));
        if("true".equals(object.getString("succ").toString())){
            return "短信发送成功";
        }
        return "短信发送失败";
    }
    @Override
    public Result  savedlyc(MoveCarEntity moveCarEntity) throws IOException{
        String url = configInfo.getServiceInterfaceAddress()+"/apphub/road";

        JSONObject object = JSON.parseObject(HttpClientUtil.doPostString(url,moveCarEntity));

        if("true".equals(object.getString("succ"))){
            return new Result(Result.SUCC,object.getString("msg"));
        }
        return new Result(Result.FAILURE,"堵路移车上传失败");

    }

    @Override
    public String  selectSjhm(RoadBlock roadBlock) throws IOException {
        String url = configInfo.getServiceInterfaceAddress() + "/querys/queryViolationNoCode?apiType="+"7" +"&hpzl=" + roadBlock.getCartype() + "&hphm="+roadBlock.getCarnum();
        JSONObject object = JSON.parseObject(HttpClientUtil.doGet(url));

        if(object.getJSONObject("data").getJSONArray("result").size()!=0 && null!=object.getJSONObject("data").getJSONArray("result")){
            return ((JSONObject)object.getJSONObject("data").getJSONArray("result").get(0)).getString("SJHM");
        }else{
            return "没有查到对方联系方式";
        }
    }
}
